'use strict';

require('../../assets/scss/entry/common.scss');
require('../../assets/scss/entry/exam.scss');

let $ = jQuery = window.jQuery = window.$ = require('jquery');
require("../../libs/Wxconfig");
require("../../libs/amazeui");
// let Intense = require('../../libs/intense.min');

import * as api from '../../components/api/index.js';
import url from '../../components/util/url.js';
import util from '../../components/util/util.js';
import Video from '../../components/video/video.js';
let Layer = require('../../libs/layer');

let pageEntry = (function() {
	let currentExamTimes = 0;
	let examQuery = null;
	let nextExamType = 0;
	let answerTime = 0;//答题时间
	let userName = localStorage.getItem('userName');
	let examCode = url.getQuery('examCode');
	let userCode = $.cookie('userCode');
	let examType = $.cookie('userType');
	let examStatus = 1;
	let questionType = 0;
	let currentExam = 0;
	let timer1 = "";
	let timer = "";//倒计时计时器
	let recordTime = 0;
	let isPlaying = 0;//0-未播放，1-播放中

	let $endNum = 0,isluyinIng = 1,isClick = 1;
	/**
	 * 播放倒计时
	 * @param time {Number} 倒计时分---按秒数来
	 * @param checkCodeBtnPlaceholder {jquery Dom} 倒计时按钮
	 */
	let countdown = (time, checkCodeBtnPlaceholder,countStatus) => {
	    checkCodeBtnPlaceholder.css("display","inline-block");
	    time=time-1;
	    timer = setInterval(function () {
		    let minute = 0, second = 0; //时间默认值
		    if (time > 0) {
		      minute = Math.floor(time / 60) ;
		      second = Math.floor(time) - (minute * 60);
		    }
		    // if (minute <= 9) minute = '0' + minute;
		    if (second <= 9) second = '0' + second;
		    $('#minute_show').html('<s></s>' + minute + '分');
		    $('#second_show').html('<s></s>' + second + '秒');
		    if(time == 0){
		    	clearTimeout(timer);
		    	if(countStatus == "2"){
		    		isPlaying = 0;
		    	}
		    	if(currentExamTimes == 0){
					$(".recording,.record-time").hide();
					$(".recorded").show();
				}else{
					$(".recordPlaying,.record-time,.recording").hide();
					$(".recorded").show();
				}
				$(".recordPlaying").hide();
		    }
		    checkCodeBtnPlaceholder.html(minute+":"+second);
		    time--;
		    if(countStatus == "1"){
		    	recordTime++;
		    	$.cookie("recordTime",recordTime,{expires: 1});
		    }
		}, 1000);
	}
	return {
		initCheck() {
			let nowUrl = window.location.href;
			util.initLogin(nowUrl,"2");
		},
		initExamInfo() {
			let explainVideo = new Video($('#J_questionExplainUrl'));
			let answerVideo = new Video($('#J_answerDemoUrl'));

			explainVideo.init();
			answerVideo.init();
			// 获取考试信息
			api.getExamInfo(userCode, userName, examCode).then((resp) => {
				if (resp.ret == "0") {
					var content = resp.content;
					var examQuestionIndex = content.paper.examQuestionIndex;

					currentExam = examQuestionIndex;
					questionType = parseInt(content.paper.questions[currentExam].questionType)-1;
					answerTime = content.paper.questions[currentExam].answerTime;
					if (examQuestionIndex == 6) {
						examStatus = 2;
					}
					else {
						nextExamType = content.paper.questions[currentExam + 1].answerWay;
					}

					examQuery = {
						studentCode: content.studentCode,
						userCode: content.userCode || '',
						organCode: content.organCode || '',
						paperId: content.paper.id,
						examType: examType,
						questionId: content.paper.questions[currentExam].id,
						examStatus: examStatus,
						questionIndex: parseInt(content.paper.examQuestionIndex) + 1
					};
					var answerDemoUrl = resp.content.paper.questions[currentExam].answerDemoUrl;
					var questionExplainUrl = resp.content.paper.questions[currentExam].questionExplainUrl;


					$('#J_exam_title').html('第'+ util.initToCapitalNumber(currentExam) +'题&nbsp;&nbsp;' + util.initExamTitle(questionType));
					$('#J_answerDemoUrl').find('[data-video-elem="player"]').attr('src', answerDemoUrl);
					$('#J_questionExplainUrl').find('[data-video-elem="player"]').attr('src', questionExplainUrl);
					var examQuestionImageExplainUrl = content.paper.questions[currentExam].questionImageExplainUrl;
					if(!util.isEmpty(examQuestionImageExplainUrl)){
						$('#J_material').find('img').attr('src', content.paper.questions[currentExam].questionImageExplainUrl);
						$('#J_material').find('img').attr('data-rel', content.paper.questions[currentExam].questionImageExplainUrl);
						$('#J_material_wrap').show();
						// Intense( $('#J_material').find('img')[0] );
					}
					if(parseInt(answerTime) > 60){
						answerTime = "60";
					}
					pageEntry.bindEvent(answerTime);
				}
		    });
		},
		initClick() {
			$(".page-re-record-btn").off("click").on("click",function(e){

				currentExamTimes++;
				if (currentExamTimes >= 3) {
					Layer.msg('最多录制2次');
				}else{
					clearTimeout(timer);
					e.stopPropagation();
					$('#J_answerDemoUrl').find('[data-video-elem="player"]')[0].pause();
					$('#J_questionExplainUrl').find('[data-video-elem="player"]')[0].pause();
					$("audio")[0].pause();
					$(".recorded,.recordPlaying").hide();
					$("#J_record_btn").click();
					// api.getExamInfo(userCode, userName, examCode).then((resp) => {
					// 	if (resp.ret == "0") {
							pageEntry.bindEvent(answerTime);
						// }
					// });
				}
			});
		},
		bindEvent(time) {
			$(".page-group-btn").hide();
			//点击录制
			$("#J_record_btn").off("click").on("click",function(e){
				recordTime = 0;
				$('#J_answerDemoUrl').find('[data-video-elem="player"]')[0].pause();
				$('#J_questionExplainUrl').find('[data-video-elem="player"]')[0].pause();
				pageEntry.initClick();
				//当前时间多少分钟
				let minutesT = Math.floor(parseInt(time/60));
				//当前时间分钟之外多少秒数
				let secondT = time%60;
				if(secondT<10){
					secondT = "0"+secondT;
				}
				if(currentExamTimes == 0){
					$(".recording .record-time").empty().html(minutesT + ":"+secondT);
				}else{
					$(".recording .record-time").empty().html(minutesT + ":"+secondT);
				}
				$(".page-single-btn").hide();
				$(".recording,.recording .record-time").show();
				$endNum++;
				e.stopPropagation();
				isluyinIng = 0;
				var timer0 = "";
				var timer2 = "";
				var isTrue = 0;
				var _that = $(this);
				function huidiao(_that){
					$('#audio').attr("src","");
					wx.ready(function(){
						var audioNum = $("audio")[0];
						audioNum.currentTime = 0;
						audioNum.pause();
					});
					// isClick = 0;
					let widVal = 0,
						leftVal = -6,
						// index = _that.attr('index'),
						curTime = _that.attr('time'),
						length = 10;
						_that.addClass('hover');
				    wx.ready(function(){
						let voice = {
						    localId: '',
						    serverId: ''
						};
							wx.startRecord({
								success:function(){
									countdown(time,$(".recording .J_record_icon .record-time"),"1");
									timer1 = setTimeout(stop,time*1000);
									isPlaying = 0;
								},
								fail: function (res) {
							        	isluyinIng = 1;
							        },
						        cancel: function () {
									Layer.msg('用户拒绝授权录音~');
						        }
						    });
					    wx.error(function(res){
					    	console.log(res);
						    // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
						});
						//length毫秒后停止录音
						function stop(){
							//重录回执
							isClick = 1;
							window.clearTimeout(timer1);
							// 4.3 停止录音
							wx.stopRecord({
						        success: function (res) {
						        	isluyinIng = 1;
						        	voice.localId = res.localId;
						        	$('#audioPlay').attr("localId",voice.localId);
						        	clearTimeout(timer);
						        	isPlaying = 0;
						        	//上传语音
								    wx.uploadVoice({
								        localId: voice.localId,
								        success: function (res) {
									        voice.serverId = res.serverId;
									        _that.attr('serverId',voice.serverId);
									        api.upload(res.serverId).then((resp) => {
									        	examQuery.answerContentUrl = resp.content.mediaUrl;
									        	$('#J_finished_btn_group,#J_next_btn_group').hide();
			        							$(".recorded,.page-group-btn-wrap,.page-group-btn").show();
									        	if (currentExam == 6) {
													// $('#J_next_btn_group').hide();
													$('#J_finished_btn_group').show();
								                }
								                else {
								                	$('#J_next_btn_group').show();
													$('#J_finished_btn_group').hide();
								                }
									        });
								        }
								    });

						        },
						        fail: function (res) {
						        	// alert(JSON.stringify(res));
						        	isluyinIng = 1;
						        }
						    });
						}
					});
				}
				// if(isClick == 1){
					huidiao(_that);
				// }
			});
			//播放音频/暂停播放
			$('#audioPlay').off("click").on("click",function(e){
				e.stopPropagation();
				isPlaying = 1;
				let time = $.cookie("recordTime");
				var _this = $(this);
				var localIds = _this.attr('localId');
				//当前时间多少分钟
				let minutesT = Math.floor(parseInt(time/60));
				//当前时间分钟之外多少秒数
				let secondT = time%60;
				if(secondT<10){
					secondT = "0"+secondT;
				}
				$(".recordPlaying .record-time").empty().html(minutesT + ":"+secondT);
				// var timelength = "10";
				// if(_this.hasClass('active')){
				// 	_this.removeClass('active');
				// 	//暂停播放音频
				//     wx.pauseVoice({
				//         localId: localIds
				//     });
				// }else{
				// 	_this.addClass('active');
				// 	//播放音频
				//     if (localIds == '') {
				//         // $tipscon.text("请先录制一段声音哦~");
				// 		// showTip();
				//         return;
				//     }
				    wx.playVoice({
				        localId: localIds,
				        success: function (res) {
					      	$(".recorded").hide();
							$(".recordPlaying,.recordPlaying .J_record_icon").show();
							countdown(recordTime,$(".recordPlaying .J_record_icon .record-time"),"2");
				        }
				    });
				// }
			});
			// });
			//停止录制
			$("#recording").off("click").on("click",function(e){
				e.stopPropagation();
				window.clearTimeout(timer1);
				let voice = {
				    localId: '',
				    serverId: ''
				};
				// 4.3 停止录音
				wx.stopRecord({
			        success: function (res) {
			        	isluyinIng = 1;
			        	voice.localId = res.localId;
			        	$('#audioPlay').attr("localId",voice.localId);
			        	clearTimeout(timer);
			        	$(".page-record-icon").hide();
			        	//上传语音
					    wx.uploadVoice({
					        localId: voice.localId,
					        success: function (res) {
						        voice.serverId = res.serverId;
						        $("#J_record_btn").attr('serverId',voice.serverId);
						        api.upload(res.serverId).then((resp) => {
						        	examQuery.answerContentUrl = resp.content.mediaUrl;
						        	$('#J_finished_btn_group,#J_next_btn_group').hide();
			        				$(".recorded,.page-group-btn-wrap,.page-group-btn").show();
						        	if (currentExam == 6) {
										$('#J_next_btn_group').hide();
										$('#J_finished_btn_group').show();
					                }
					                else {
					                	$('#J_next_btn_group').show();
										$('#J_finished_btn_group').hide();
					                }
						        });
					        }
					    });
			        },
			        fail: function (res) {
			        	isluyinIng = 1;
			        }
			    });
			});
			// 下一题
			$('#J_next_btn').off("click").on('click', function() {
				if(isPlaying == 1){
					Layer.msg('请等待录音播放完毕再提交');
				}else{
					api.setExamInfo(examQuery).then((resp) => {
						if (resp.ret == "0") {
							if (nextExamType == 1) {
								window.location.href = '/examAudio.html?examCode=' + examCode;
							}
							else if (nextExamType == 2) {
								window.location.href = '/examVideo.html?examCode=' + examCode;
							}
						}
					});
				}
			});

			// 提交
			$('#J_finished_btn').off("click").on('click', function() {
				if(isPlaying == 1){
					Layer.msg('请等待录音播放完毕再提交');
				}else{
					api.setExamInfo(examQuery).then((resp) => {
						if (resp.ret == "0") {
							if (resp.ret == "0") {
								Layer.msg('您的试卷已经成功提交</br>请耐心等待评审结果');
					            setTimeout(function(){
					                window.location.href = "/indiviInfo.html";
					            },3000);
							}
						}
					});
				}

			});
		}
	}
})();

pageEntry.initCheck();
pageEntry.initExamInfo();
// pageEntry.bindEvent();
